# -*- coding:utf-8 -*-
import json
import os

from common.db import session, Record
from common.import_pyside import *
from common.data import DB
from execute import Run
from record.components.cus_signal import CusSignal


class Main(QWidget):
    # 点击侧边任务名称
    click_current_case_task_name = Signal()

    def __init__(self, parent=None):
        super(Main, self).__init__(parent=parent)

        mainlayout = QVBoxLayout()

        # ############### 顶部按钮组   ########################
        groupBox = QGroupBox('任务操作', self)
        groupBox.setFixedHeight(70)
        buttonlayout = QHBoxLayout()
        runButton = QPushButton("执行")
        runButton.setFixedSize(100, 20)
        uploadButton = QPushButton("上传")
        uploadButton.setFixedSize(100, 20)
        saveButton = QPushButton("保存")
        saveButton.setFixedSize(100, 20)
        deleteButton = QPushButton("删除")
        deleteButton.setFixedSize(100, 20)

        buttonlayout.addWidget(runButton)
        buttonlayout.addWidget(uploadButton)
        buttonlayout.addWidget(saveButton)
        buttonlayout.addWidget(deleteButton)

        groupBox.setLayout(buttonlayout)

        # ##########    中间
        layout = QVBoxLayout()

        self.MainTableWidget = QTableWidget()

        #
        # # 设置表头
        # table_header_list = ['类型', '动作', '按钮', '坐标', '持续时间']
        # for index, item in enumerate(table_header_list):
        #     self.tableWidget.setHorizontalHeaderItem(index, QTableWidgetItem(item))
        self.MainTableWidget.setColumnCount(6)
        self.MainTableWidget.setRowCount(1)
        self.MainTableWidget.resizeColumnsToContents()

        self.MainTableWidget.setHorizontalHeaderLabels(['类型', '动作', '按钮', '坐标x', '坐标y', '持续时间'])
        # 参考地址：http://phpzyw.com/bc5a5B2wHB1VXBAM.html
        self.MainTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.MainTableWidget.setAutoFillBackground(True)

        self.num = 10
        self.add_table_data()

        # 允许点击发送信号
        self.MainTableWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        # 设置上下文菜单请求事件
        self.MainTableWidget.customContextMenuRequested.connect(self.generateMenu)

        layout.addWidget(self.MainTableWidget)
        mainlayout.addWidget(groupBox)
        mainlayout.addLayout(layout)
        self.setLayout(mainlayout)


        # self.click_current_case_task_name.connect(self.add_table_data())


    def add_table_data(self):
        current_case_data = {}
        current_case_data_cases = []

        if DB.current_case_task_name:
            instance = session.query(Record).filter(Record.case_name == DB.current_case_task_name).first()
            current_case_data = json.loads(instance.case_data)
            current_case_data_cases = current_case_data["cases"]

        case_len = len(current_case_data_cases)
        print(self.num)


        # self.tableWidget.setRowCount(20)
        self.MainTableWidget.setRowCount(case_len)

        # for row in range(case_len):
        #     # 第一列，启用/禁用选择
        #     cmbState = QComboBox()
        #     cmbState.addItem('Disabled')
        #     cmbState.addItem('Enabled')
        #     cmbState.setCurrentIndex(0)
        #     self.MainTableWidget.setCellWidget(row, 0, cmbState)
        #
        #     itemWidget = QTableWidgetItem("2323")
        #     itemWidget.setToolTip("233434")
        #     self.MainTableWidget.setItem(row, 1, itemWidget)
        # self.MainTableWidget.show()


        for row in range(case_len):
            # 第一列，启用/禁用选择
            cmbState = QComboBox()
            cmbState.addItem('Disabled')
            cmbState.addItem('Enabled')
            cmbState.setCurrentIndex(0)
            self.MainTableWidget.setCellWidget(row, 0, cmbState)
            # 第二列，起始值
            startVal = QLineEdit('0.0')
            startVal.setAlignment(Qt.AlignHCenter)
            self.MainTableWidget.setCellWidget(row, 1, startVal)
            # 第三列，结束值
            stopVal = QLineEdit('100.0')
            stopVal.setAlignment(Qt.AlignHCenter)
            self.MainTableWidget.setCellWidget(row, 2, stopVal)
            # 第四列，复选按钮,居中排列
            chkBox = QCheckBox('相对值')
            chkBox.setChecked(True)
            hLayout = QHBoxLayout()
            widget = QWidget(self.MainTableWidget)
            hLayout.addWidget(chkBox)
            hLayout.setContentsMargins(0, 0, 0, 0)
            hLayout.setAlignment(Qt.AlignHCenter)
            widget.setLayout(hLayout)
            self.MainTableWidget.setCellWidget(row, 3, widget)

    def generateMenu(self, pos):

        # for i in self.tableWidget.selectionModel().selection().indexes():
        # 选择的行索引
        #     rowNum = i.row()
        # 如果选择的行索引小于2，弹出上下文菜单

        menu = QMenu(self)
        inset_before = QAction("在该步骤前插入", self)
        inset_before.setIcon(QIcon('./icon/stop_record.ico'))

        inset_after = QAction("在该步骤后插入", self)
        inset_after.setIcon(QIcon('./icon/stop_record.ico'))

        item3 = QAction("在该步骤前插入", self)
        item3.setIcon(QIcon('./icon/stop_record.ico'))

        menu.addAction(inset_before)
        menu.addAction(inset_after)
        menu.addSeparator()
        menu.addAction(item3)
        screenPos = self.MainTableWidget.mapToGlobal(pos)
        # 在当前步骤阻塞
        action = menu.exec_(screenPos)
        if action == item3:
            print("3")
            # list数据，当前已选择的itemModel,列表
            self.MainTableWidget.selectedIndexes()


if __name__ == '__main__':
    app = QApplication()
    win = Main()
    win.show()
    app.exec()
